package com.newegg.sshd;

import java.io.IOException;
import org.apache.sshd.server.Environment;
import org.apache.sshd.server.ExitCallback;
import org.apache.sshd.server.channel.ChannelSession;
import org.jline.terminal.Terminal;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.JCommander.Builder;
import com.beust.jcommander.Parameter;

public abstract class AbstractCommand {
	protected ChannelSession channel;
	protected ExitCallback callback;
    protected Environment environment;
    protected Thread cmdRunner;
    protected Terminal terminal;
    
	protected String command = "";
	
	@Parameter(names = {"--help", "?"}, description = "help")
    protected boolean help = false;
	
	public static <T extends AbstractCommand> T getInstance(Class<T> clazz, String command){
		try {
			T t = clazz.newInstance();
			t.initParams(command, t, true);
			return t;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	protected <T extends AbstractCommand> void initParams(String command, T obj,  boolean acceptUnknownOptions) {
		Builder builder = JCommander.newBuilder().addObject(this);
		String[] args = new String[0];
		if(command != null && !"".equals(command)) {
			this.command = command;
			args = command.split(" ");
		}
		builder.acceptUnknownOptions(acceptUnknownOptions).build().parse(args);
	}
	
	public abstract String run() throws IOException;
	
	public void echo(String msg){
		if(terminal == null) { return; }
		terminal.writer().println(msg);
		terminal.writer().flush();
	}
	
	public String help() {
		StringBuilder stringBuilder = new StringBuilder();
		JCommander.newBuilder()
			.addObject(this)
			.programName(this.getClass().getSimpleName().toLowerCase())
			.build()
			.getUsageFormatter()
			.usage(stringBuilder);
		return stringBuilder.toString().replace("\n", "\r\n");
	}
	
	public void setHelp(boolean help) {
		this.help = help;
	}
}
